using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using SolanumSolstice.Units;
using SolanumSolstice.Units.Weapons;
using SolanumSolstice.Mapping;

namespace SolanumSolstice.Buildings
{
    public class ResearchTree
    {

        private int civilianLevel;
        private int militaryLevel;
        private int scienceLevel;
        private bool xIsPressed;
        private ResearchBuilding researchBuilding;
        private Texture2D background;
        private Texture2D node;
        private Texture2D lockedNode;
        private Texture2D connector;
        private Texture2D militaryPic;
        private Texture2D sciencePic;
        private Texture2D civilianPic;
        private Texture2D emptyBar;
        private Texture2D fullBar;
        private SpriteFont spriteFont;
        private SpriteFont medFont;
        private ContentManager m_content;
        
        private int civStartX = 150;
        private int milStartX = 150;
        private int sciStartX = 150;
        
        private int civStartY = 150;
        private int milStartY = 205;
        private int sciStartY = 260;
        //private List<string> description;
        string description = "";
        string shortdesc = "";

        //the descriptions are done.  Just need tweaking.
        string[,] researchStrings = {{  "Scavenging\nIncreased perception of food items\nGather ability up",
                                        "Carpentry\nNow Johnny works with two hammers!\nBuild/Repair ability up",
                                        "Subsister\nCivilians get tougher and learn to eat snakes\nUnit upgrade",
                                        "Punji Log\nA deadly log of spikes. Kills 5 Zombies\nUnlock Trap",
                                        "Scouting\nEnhanced awareness and enemy detection\nSight ability up",
                                        "Survivialist\nStrong, deadly survivors who can handle a gun\nUnit upgrade",
                                        "Adv. Carpentry\nBuild and Repair fences in a flash\nBuild/Repair ability up",
                                        "Gunman\nHandle a pistol like a cop\nGain Cop's Pistol ability",
                                        "Pathfinder\nInnate knowledge of region\nFull Map Reveal",
                                        "Escape\n Research how to start a new Human Utopia in the mountains\nCleanse the Mall to find the Zombie Survival Guide!"},
                                     {  "Pistols\nCops get off the beat and armed for action\nWeapon Upgrade",
                                        "SWAT Protocol\nCops follow orders more efficiently in buildings\nCleansing ability up",
                                        "Soldier\nCops turn in their badges for stripes. Ten Hut!\nUnit Upgrade",
                                        "Shotgun\nThis... is my BOOM-stick! Come get some.\nWeapon Upgrade",
                                        "BioScan\nHUD measures Zombies' functional neuron mass\n See Zombies HP",
                                        "Rifle\nEngage Zombies at a distance\nWeapon Upgrade",
                                        "Special Ops\nElite forces with advanced combat tactics\nUnit Upgrade",
                                        "Decimation\nCleanse a building with no casualties\nCleanse ability up",
                                        "Rocket Launcher\nLong-distance, high-yield explosive fun\nWeapon Upgrade ",
                                        "Nuclear Detonation\nResearch how to explode the power plant\nCleanse the Power Plant to Nuke the city!"},
                                     {  "Chain-link Fence\nMore durable than wood fences\nUpgrade barrier",
                                        "Speed Reading\nScientists research faster\nResearch Up",
                                        "Scholar\nOn the tenure track.  Research is his life!\nUnit Upgrade",
                                        "First Aid\nScientests Heal Damaged Units\nHeal other Units   ",
                                        "Electric Fence\nZap 'em like bugs! Toasty!\nBarrier Upgrade",
                                        "Motion Sensor\nBeacon can detect survivors and zombies\nMap Upgrade",
                                        "Genius\nMENSA savants with extreme research skills\nUnit Upgrade",
                                        "Acid Pools\n Dissolves zombie's flesh.  Mmm, mmm good!\n Trap Lv2",
                                        "Maximum Heal\n Heal units to their max HP\nHealing ability up",
                                        "Cure the Zombies\nDIscover how to revert zombies back to people\nCleanse the hospital to find The Cure!"}};
        public void debugcode()
        {

            //only reveals - to get the upgrades, iterate through and call Upgrade(x)
            for (int i = 0; i < 9; i++)
            {
                civilianLevel++;
                scienceLevel++;
                militaryLevel++;
                Upgrade(UnitClass.Science);
                Upgrade(UnitClass.Military);
                Upgrade(UnitClass.Civilian);
            }
            
        }

        public void Upgrade(UnitClass unit)
        {
            Beacon b = SolanumSolstice.getBeacon();
            if (unit == UnitClass.Civilian)
            {
                switch (civilianLevel - 1)
                {
                    case 0:  //gather ability up
                        b.CivArchetype.GatherTime = (b.CivArchetype.GatherTime * 0.5f);
                        b.SubArchetype.GatherTime = (b.SubArchetype.GatherTime * 0.5f);
                        b.SurvArchetype.GatherTime = (b.SurvArchetype.GatherTime * 0.5f);
                        break;

                    case 1:  //repair upgrade 1
                        b.CivArchetype.RepairPower = b.CivArchetype.RepairPower * 2;
                        b.SubArchetype.RepairPower = b.SubArchetype.RepairPower * 2;
                        b.SurvArchetype.RepairPower = b.SurvArchetype.RepairPower * 2;
                        break;

                    case 2:  //Unit Upgrade
                        b.SubsistorIsLocked = false;
                        break;

                    case 3:  //set traps
                        SolanumSolstice.trapUnlocked = true;
                        break;

                    case 4:  //see more of map
                        b.SubArchetype.SightRadius = b.CivArchetype.SightRadius * 2;
                        b.CivArchetype.SightRadius = b.SubArchetype.SightRadius * 2;
                        b.SurvArchetype.SightRadius = b.SurvArchetype.SightRadius * 2;
                        break;

                    case 5:  //repair upgrade 2
                        b.CivArchetype.RepairPower = b.CivArchetype.RepairPower * 2;
                        b.SubArchetype.RepairPower = b.SubArchetype.RepairPower * 2;
                        b.SurvArchetype.RepairPower = b.SurvArchetype.RepairPower * 2;
                        break;

                    case 6:  //unit upgrade
                        b.SurvivalistIsLocked = false;
                        break;

                    case 7:  //cop's gun ability
                        b.SurvArchetype.Weapon = new Pistol(m_content);
                        break;

                    case 8:  //reveal map
                        Map.setAllVisible();
                        break;

                    case 9:  //radio for help / escape
                        foreach (Building building in SolanumSolstice.buildings)
                        {
                            if (building.BuildingType == BuildingType.Spawn)
                            {
                                Spawn spawn = (Spawn)building;
                                if (spawn.UnitType == UnitClass.Civilian)
                                {
                                    spawn.IsInfested = true;
                                    for (int i = 0; i < 20; i++)
                                    {
                                        ZombieCivilian zom = new ZombieCivilian(m_content, spawn.Position);
                                        zom.InBuilding = true;
                                        spawn.Zombies.Add(zom);
                                    }
                                }
                            }
                        }                        
                        SolanumSolstice.CivilianWinEnabled = true;
                        break;

                    default:

                        break;
                }
            }
            else if (unit == UnitClass.Military)
            {
                switch (militaryLevel - 1)
                {
                    //Pistol Upgrade
                    case 0:    
                            b.CopArchetype.Weapon = new Pistol(m_content); 
                        break;

                    //cleansing power up
                    case 1:
                        foreach (Building bild in SolanumSolstice.buildings)
                        {
                            bild.CleanseMultiplier = 1.5f;
                        }
                        break;

                    //unit upgrade
                    case 2: b.SoldierIsLocked = false;
                        break;

                    //shotgun
                    case 3: b.SldArchetype.Weapon = new Shotgun(m_content);
                        break;

                    //see zombie hp
                    case 4:
                        SolanumSolstice.showEnemyHP = true;
                        break;

                    //unit upgrade
                    case 5: b.SpecOpIsLocked = false;
                        break;

                    //rifle
                    case 6: b.SoArchetype.Weapon = new Rifle(m_content);
                        break;

                    //zero cleanse time - attackmultiplier 
                    case 7:
                        foreach (Building bild in SolanumSolstice.buildings)
                        {
                            bild.CleanseMultiplier = 2.0f;
                        }
                        break;

                    //rocket launcher
                    case 8:
                        b.SoArchetype.Weapon = new RocketLauncher(m_content);
                        break;

                    //detonate nuke
                    case 9:
                        foreach (Building building in SolanumSolstice.buildings)
                        {
                            if (building.BuildingType == BuildingType.Spawn)
                            {
                                Spawn spawn = (Spawn)building;
                                if (spawn.UnitType == UnitClass.Military)
                                {
                                    spawn.IsInfested = true;
                                    for (int i = 0; i < 20; i++)
                                    {
                                        ZombieSoldier zom = new ZombieSoldier(m_content, spawn.Position);
                                        zom.InBuilding = true;
                                        spawn.Zombies.Add(zom);
                                    }
                                }
                            }
                        }
                        SolanumSolstice.MilitaryWinEnabled = true;
                        break;

                    default:
                        break;
                }
            }
            else if (unit == UnitClass.Science)
            {
                switch (scienceLevel - 1)
                {
                    //wood fence to chainlink fence
                    case 0:
                        SolanumSolstice.chainLinkFenceUnlocked = true;
                        break;

                    //more research power
                    case 1: b.RschArchetype.ResearchPower = (b.RschArchetype.ResearchPower * 2);
                        break;

                    //unit upgrade
                    case 2: b.ScholarIsLocked = false;
                        break;

                    //healing people
                    case 3: b.SchArchetype.HealPower = (b.SchArchetype.HealPower * 2);
                        break;

                    //electric Fence
                    case 4:
                        SolanumSolstice.electricFenceUnlocked = true;
                        break;

                    //detect survivors/zombies
                    case 5:
                        SolanumSolstice.detectZombiesUnlocked = true;
                        break;

                    // unit upgrade
                    case 6:
                        b.GeniusIsLocked = false;
                        break;

                    // Acid Trap
                    case 7:
                        SolanumSolstice.trapUnlocked = true;
                        SolanumSolstice.acidTrapUnlocked = true;
                        break;

                    //Max Cure
                    case 8:
                        b.GenArchetype.HealPower = 99;
                        b.RschArchetype.HealPower = 99;
                        b.SchArchetype.HealPower = 99;
                        break;

                    case 9: // find a cure
                        foreach (Building building in SolanumSolstice.buildings)
                        {
                            if (building.BuildingType == BuildingType.Spawn)
                            {
                                Spawn spawn = (Spawn)building;
                                if (spawn.UnitType == UnitClass.Science)
                                {
                                    spawn.IsInfested = true;
                                    for (int i = 0; i < 20; i++)
                                    {
                                        ZombieScientist zom = new ZombieScientist(m_content, spawn.Position);
                                        zom.InBuilding = true;
                                        spawn.Zombies.Add(zom);
                                    }
                                }
                            }
                        }
                        SolanumSolstice.ScienceWinEnabled = true;
                        break;

                    default:
                        break;
                }
            }
        }



        #region Accessors
        public int CivilianLevel
        {
            get
            {
                return civilianLevel;
            }
            set
            {
                civilianLevel = value;
            }
        }
        public int MilitaryLevel
        {
            get
            {
                return militaryLevel;
            }
            set
            {
                militaryLevel = value;
            }
        }
        public int ScienceLevel
        {
            get
            {
                return scienceLevel;
            }
            set
            {
                scienceLevel = value;
            }
        }

        #endregion

        //returns a string of all description lines
        public string getDescription(UnitClass unit, int level)
        {
            int unitindex = 1;
            if (unit == UnitClass.Civilian) { unitindex = 0; }
            if (unit == UnitClass.Military) { unitindex = 1; }
            if (unit == UnitClass.Science) { unitindex = 2; }

            return researchStrings[unitindex, level];
        }

        //returns a string of the first description line
        public string GetDescription(UnitClass unit)
        {
            int level = 0;
            int unitindex = 0;
            if (unit == UnitClass.Civilian) { unitindex = 0; level = civilianLevel - 1; }
            if (unit == UnitClass.Military) { unitindex = 1; level = militaryLevel - 1; }
            if (unit == UnitClass.Science) { unitindex = 2; level = scienceLevel - 1; }

            string s = researchStrings[unitindex, level];
            int index = s.IndexOf("\n");
            s = s.Substring(0, index);
            return s;
        }


        public string getString(string s, int n)
        {   
            int index=0, previndex=0;
            while (n>0) {
              previndex=index;
              index = s.IndexOf("\n");
              n--;
            }    

            return s.Substring(previndex, index);

        }

        public ResearchTree(ContentManager content, ResearchBuilding building)
        {
            civilianLevel = 0;
            militaryLevel = 0;
            scienceLevel = 0;
            researchBuilding = building;
            background = content.Load<Texture2D>("Content\\Txtr\\Sys\\ResearchTree\\researchTreeBG");
            node = content.Load<Texture2D>("Content\\Txtr\\Sys\\ResearchTree\\researchNode");
            connector = content.Load<Texture2D>("Content\\Txtr\\Sys\\ResearchTree\\researchconnector");
            xIsPressed = false;

            militaryPic = content.Load<Texture2D>("Content\\Txtr\\Units\\HUD\\copHUD");
            sciencePic = content.Load<Texture2D>("Content\\Txtr\\Units\\HUD\\researcherHUD");
            civilianPic = content.Load<Texture2D>("Content\\Txtr\\Units\\HUD\\civHUD");

            lockedNode = content.Load<Texture2D>("Content\\Txtr\\Sys\\ResearchTree\\lockedNode");

            emptyBar = content.Load<Texture2D>("Content\\Txtr\\Units\\EmptyBar");
            fullBar = content.Load<Texture2D>("Content\\Txtr\\Units\\FullBarWhite");
            spriteFont = content.Load<SpriteFont>("Content\\Fnt\\ArialMedium");
            medFont = content.Load<SpriteFont>("Content\\Fnt\\ArialSmall");
            m_content = content;

            if (SolanumSolstice.DEBUGMODE) debugcode();

        }

        public void Update(GameTime gameTime, GamePadState gamePad, GameCursor gameCursor)
        {

            if (gamePad.Buttons.X == ButtonState.Pressed)
            {
                if (xIsPressed == false)
                {
                    if (researchBuilding.IsResearching == false)
                    {
                        //this is where the clicking changes.
                        if (gameCursor.ScreenPositionX > civStartX - 50 && gameCursor.ScreenPositionX < civStartX)
                        {
                            if (gameCursor.ScreenPositionY > civStartY && gameCursor.ScreenPositionY < civStartY + 40)
                            {
                                researchBuilding.StartNewResearch(UnitClass.Civilian);
                            }
                            else if (gameCursor.ScreenPositionY > milStartY && gameCursor.ScreenPositionY < milStartY + 40)
                            {
                                researchBuilding.StartNewResearch(UnitClass.Military);
                            }
                            else if (gameCursor.ScreenPositionY > sciStartY && gameCursor.ScreenPositionY < sciStartY + 40)
                            {
                                researchBuilding.StartNewResearch(UnitClass.Science);
                            }
                        }
                    }
                }

                xIsPressed = true;

            }
            else
            {
                xIsPressed = false;



                if (gameCursor.ScreenPositionY > civStartY && gameCursor.ScreenPositionY < civStartY + 50)
                {
                    for (int x = 0; x <= civilianLevel; x++)
                    {
                        if (x < 10)
                        {
                            if (gameCursor.ScreenPositionX >= (x * 50 + civStartX)
                                && gameCursor.ScreenPositionX <= (x * 50 + civStartX + 50))
                            {
                                description = getDescription(UnitClass.Civilian, x);
                                shortdesc = getString(description, 1);
                            }
                        }
                    }
                }
                else if (gameCursor.ScreenPositionY > milStartY && gameCursor.ScreenPositionY < milStartY + 50)
                {
                    for (int x = 0; x <= militaryLevel; x++)
                    {
                        if (x < 10)
                        {
                            if (gameCursor.ScreenPositionX >= (x * 50 + milStartX)
                                && gameCursor.ScreenPositionX <= (x * 50 + milStartX + 50))
                            {
                                description = getDescription(UnitClass.Military, x);
                                shortdesc = getString(description, 1);

                            }
                        }
                    }
                }
                else if (gameCursor.ScreenPositionY > sciStartY && gameCursor.ScreenPositionY < sciStartY + 50)
                {
                    for (int x = 0; x <= scienceLevel; x++)
                    {
                        if (x < 10)
                        {
                            if (gameCursor.ScreenPositionX >= (x * 50 + sciStartX)
                                && gameCursor.ScreenPositionX <= (x * 50 + sciStartX + 50))
                            {
                                description = getDescription(UnitClass.Science, x);
                                shortdesc = getString(description, 1);
                            }
                        }
                    }
                }




            }

        }

        public void drawLocked (SpriteBatch spritebatch, string shortdesc, int x, int y, Color col) {
            spritebatch.Draw(lockedNode, new Vector2(x,y), col);
            //Vector2 meas = medFont.MeasureString(shortdesc);
            //spritebatch.DrawString(medFont, shortdesc, new Vector2(x-(meas.X/2),y+100), Color.White);
        }

        public void Draw(SpriteBatch spritebatch)
        {

            int nodeOffset = 5;

            float researchPercent = (float)researchBuilding.TotalResearch / (float)researchBuilding.ResearchNeeded;


            spritebatch.Draw(background, new Rectangle(40, 40, 650, 400), Color.White);

            spritebatch.DrawString(spriteFont, "RESEARCH TREE", new Vector2(275, 60), Color.Yellow);

            spritebatch.DrawString(medFont, "Researching", new Vector2(90, 90), Color.White);


            Color pictureColor = Color.White;

            if (researchBuilding.IsResearching)
            {
                pictureColor = Color.Gray;
            }

            spritebatch.Draw(civilianPic, new Rectangle(civStartX - 50, civStartY, 40, 40), pictureColor);
            spritebatch.Draw(militaryPic, new Rectangle(milStartX - 50, milStartY, 40, 40), pictureColor);
            spritebatch.Draw(sciencePic, new Rectangle(sciStartX - 50, sciStartY, 40, 40), pictureColor);

            if (researchBuilding.IsResearching)
            {
                if (researchBuilding.UnitClassResearch == UnitClass.Civilian)
                {
                    spritebatch.Draw(civilianPic, new Rectangle(civStartX - 50, civStartY, 40, 40), Color.LightGreen);
                    //spritebatch.DrawString(medFont, "   Civilian Lvl: " + (civilianLevel)+"\n("+curr shortdesc+", new Vector2(90, 110), Color.White);
                    
                }
                else if (researchBuilding.UnitClassResearch == UnitClass.Military)
                {
                    spritebatch.Draw(militaryPic, new Rectangle(milStartX - 50, milStartY, 40, 40), Color.LightGreen);
                    spritebatch.DrawString(medFont, "Military Lvl: " + (militaryLevel), new Vector2(90, 110), Color.White);
                }
                else if (researchBuilding.UnitClassResearch == UnitClass.Science)
                {
                    spritebatch.Draw(sciencePic, new Rectangle(sciStartX - 50, sciStartY, 40, 40), Color.LightGreen);
                    spritebatch.DrawString(medFont, "Science Lvl: " + (scienceLevel), new Vector2(90, 110), Color.White);
                }
            }



            if (civilianLevel == 0)
            {
                drawLocked(spritebatch, shortdesc, civStartX, civStartY + nodeOffset, Color.White);
                //spritebatch.Draw(lockedNode, new Vector2(civStartX, civStartY + nodeOffset), Color.White);
                //spritebatch.DrawString(spriteFont, shortdesc, new Vector2(100,330), Color.Green;
            }

            if (militaryLevel == 0)
            {
                drawLocked(spritebatch, shortdesc, milStartX, milStartY + nodeOffset, Color.White);
                //spritebatch.Draw(lockedNode, new Vector2(milStartX, milStartY + nodeOffset), Color.White);
            }

            if (scienceLevel == 0)
            {
                drawLocked(spritebatch, shortdesc, milStartX, sciStartY + nodeOffset, Color.White);
                spritebatch.Draw(lockedNode, new Vector2(sciStartX, sciStartY + nodeOffset), Color.White);
            }

            for (int x = 0; x < civilianLevel; x++)
            {
                if (x > 0)
                {
                    spritebatch.Draw(connector, new Rectangle(x * 50 + civStartX - 20, civStartY + 17, (int)(researchPercent * 50), 10), new Rectangle(0, 0, (int)(researchPercent * 50), 10), Color.White);


                }

                if ((x == civilianLevel - 1) && x < 9)
                {
                    drawLocked(spritebatch,shortdesc, x * 50 + civStartX + 50, civStartY + nodeOffset, Color.White);
                    //spritebatch.Draw(lockedNode, new Vector2(x * 50 + civStartX + 50, civStartY + nodeOffset), Color.White);
                }


                spritebatch.Draw(node, new Vector2(x * 50 + civStartX, civStartY + nodeOffset), Color.White);
            }

            for (int x = 0; x < militaryLevel; x++)
            {
                if (x > 0)
                {
                    spritebatch.Draw(connector, new Rectangle(x * 50 + civStartX - 20, milStartY + 17, (int)(researchPercent * 50), 10), new Rectangle(0, 0, (int)(researchPercent * 50), 10), Color.White);
                }

                if ((x == militaryLevel - 1) && x < 9)
                {
                    drawLocked(spritebatch, shortdesc, x * 50 + milStartX + 50, milStartY + nodeOffset, Color.White);
                    //spritebatch.Draw(lockedNode, new Vector2(x * 50 + milStartX + 50, milStartY + nodeOffset), Color.White);
                    //CHANGES
                    
                }

                spritebatch.Draw(node, new Vector2(x * 50 + milStartX, milStartY + nodeOffset), Color.White);
            }

            for (int x = 0; x < scienceLevel; x++)
            {
                if (x > 0)
                {

                    spritebatch.Draw(connector, new Rectangle(x * 50 + sciStartX - 20, sciStartY + 17, (int)(researchPercent * 50), 10), new Rectangle(0, 0, (int)(researchPercent * 50), 10), Color.White);
                }

                if ((x == scienceLevel - 1) && x < 9)
                {
                    drawLocked(spritebatch, shortdesc, x * 50 + sciStartX + 50, sciStartY + nodeOffset, Color.White);
                    //spritebatch.Draw(lockedNode, new Vector2(x * 50 + sciStartX + 50, sciStartY + nodeOffset), Color.White);
                }

                spritebatch.Draw(node, new Vector2(x * 50 + sciStartX, sciStartY + nodeOffset), Color.White);
            }

            spritebatch.DrawString(spriteFont, "Research Description: ", new Vector2(100, 300), Color.White);


            spritebatch.DrawString(spriteFont, description, new Vector2(100, 330), Color.White);
            spritebatch.DrawString(spriteFont, shortdesc, new Vector2(100,330), Color.Green);

            Color researchColor = Color.Green;

            int researchBarLength = (int)(researchPercent * 400);

            if (researchBuilding.TotalResearch < ((researchBuilding.ResearchNeeded * 2) / 3))
            {
                researchColor = Color.Yellow;
            }
            if (researchBuilding.TotalResearch < (researchBuilding.ResearchNeeded / 3))
            {
                researchColor = Color.Red;
            }

            spritebatch.Draw(emptyBar, new Rectangle(200, 100, 400, 30), Color.White);
            spritebatch.Draw(fullBar, new Rectangle(200, 100, researchBarLength, 30), researchColor);


        }



    }
}


